package client

import (
	"context"
	"google.golang.org/grpc"
	"study-plan/common/proto/study"
)

type Handler func(ctx context.Context, in study.StudyClient) (interface{}, error)

func StudyClient(ctx context.Context, handler Handler) (interface{}, error) {
	dial, err := grpc.Dial("127.0.0.1:8008", grpc.WithInsecure())
	if err != nil {
		return nil, err
	}
	client := study.NewStudyClient(dial)
	res, err := handler(ctx, client)
	if err != nil {
		return nil, err
	}
	defer dial.Close()
	return res, nil
}

// todo:用户注册
func UserRegister(ctx context.Context, i *study.UserRegisterRequest) (*study.UserRegisterResponse, error) {
	client, err := StudyClient(ctx, func(ctx context.Context, in study.StudyClient) (interface{}, error) {
		res, err := in.UserRegister(ctx, i)
		if err != nil {
			return nil, err
		}
		return res, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*study.UserRegisterResponse), nil
}

// todo:用户登录
func UserLogin(ctx context.Context, i *study.UserLoginRequest) (*study.UserLoginResponse, error) {
	client, err := StudyClient(ctx, func(ctx context.Context, in study.StudyClient) (interface{}, error) {
		res, err := in.UserLogin(ctx, i)
		if err != nil {
			return nil, err
		}
		return res, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*study.UserLoginResponse), nil
}

// todo:购物车查询
func CarList(ctx context.Context, i *study.CarListRequest) (*study.CarListResponse, error) {
	client, err := StudyClient(ctx, func(ctx context.Context, in study.StudyClient) (interface{}, error) {
		res, err := in.CarList(ctx, i)
		if err != nil {
			return nil, err
		}
		return res, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*study.CarListResponse), nil
}

// todo:购物车添加
func CarCreate(ctx context.Context, i *study.CarCreateRequest) (*study.CarCreateResponse, error) {
	client, err := StudyClient(ctx, func(ctx context.Context, in study.StudyClient) (interface{}, error) {
		res, err := in.CarCreate(ctx, i)
		if err != nil {
			return nil, err
		}
		return res, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*study.CarCreateResponse), nil
}

// todo:购物车移除课程
func CarDelCourse(ctx context.Context, i *study.CarDelCourseRequest) (*study.CarDelCourseResponse, error) {
	client, err := StudyClient(ctx, func(ctx context.Context, in study.StudyClient) (interface{}, error) {
		res, err := in.CarDelCourse(ctx, i)
		if err != nil {
			return nil, err
		}
		return res, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*study.CarDelCourseResponse), nil
}

// todo:订单创建
func OrderCreate(ctx context.Context, i *study.OrderCreateRequest) (*study.OrderCreateResponse, error) {
	client, err := StudyClient(ctx, func(ctx context.Context, in study.StudyClient) (interface{}, error) {
		res, err := in.OrderCreate(ctx, i)
		if err != nil {
			return nil, err
		}
		return res, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*study.OrderCreateResponse), nil
}
